import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @作者 ： pwx5328113 @时间： 2023/3/11
 * @测试点: 打开快速负载均衡，url分别连接同一集群3个节点，并发进行连接，最小负载功能正常
 **/
public class JDBC_QuikAutoBalance_Case0037 {
	public static List<Connection> connections;

	public static void main(String[] args) throws Exception {
		// start前，包含3个节点，状态正常
		System.out.println("----------start----------");

		for (int i = 0; i < 50; i++) {
			Thread t = new Thread() {
				List<Connection> item;

				public void run() {
					try {
						System.out.println(new Date() + ":thread " + getId() + " run...");
						item = GetConnection(args[0], args[1], args[2], args[3], args[4]);
						System.out.println(new Date() + ":thread " + getId() + " connected...");
						TimeUnit.SECONDS.sleep(30);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						for (Connection connection : item) {
							try {
								connection.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						}
						System.out.println(new Date() +":thread " + getId() + " end.");
					}
				}
			};
			t.start();
		}
		System.out.println("----------等待40s----------");
		TimeUnit.SECONDS.sleep(40);
	}

	public static List<Connection> GetConnection(String url_host, String db_name, String user_name, String user_pwd,
			String url) {
		List<Connection> connections1 = new ArrayList<>();
		String url1 = "jdbc:postgresql://" + url_host + "/" + db_name + "?" + url;
		for (int i = 0; i < 18; i++) {
			try {
				Connection connection = DriverManager.getConnection(url1, user_name, user_pwd);
				connections1.add(connection);
			} catch (SQLException e) {
				e.printStackTrace();
				return null;
			}
		}
		return connections1;
	}
}
